<?php

namespace App\Http\Controllers\Home;

use App\Models\Brand;
use App\Models\Goods;
use App\Models\GoodsCategory;
use App\Models\Member;
use App\Models\MemberWaterBill;
use App\Models\Notice;
use App\Models\Order;
use App\Models\Picture;
use App\Models\PrivateCode;
use App\Models\ReferCode;
use App\Models\SaoPay;
use App\Models\Shop;
use App\Models\ShopAccount;
use App\Models\ShopGoods;
use App\Models\SmsLog;
use App\Models\WaterBill;
use App\Models\WaterBillOrder;
use App\Models\WechatSet;
use App\Support\WechatLogin;
use App\Support\WechatSilentAuth;


/**
 * 前台首页控制器
 */
class IndexController extends BaseController
{

    public function __construct(
        Shop $shop,
        Goods $goods,
        GoodsCategory $goodsCategory,
        Brand $brand,
        Picture $picture,
        ShopGoods $shopGoods,
        WaterBill $waterBill,
        MemberWaterBill $memberWaterBill,
        Order $order,
        WechatSet $wechatSet,
        Member $member,
        Notice $notice,
        WaterBillOrder $waterBillOrder,
        ShopAccount $shopAccount,
        SmsLog $smsLog,
        WechatSilentAuth $silentAuth,
        PrivateCode $privateCode,
        ReferCode $referCode,
        SaoPay $saoPay
    )
    {
        parent::__construct();
        $this->shop = $shop;
        $this->goods = $goods;
        $this->goodsCategory = $goodsCategory;
        $this->brand = $brand;
        $this->picture = $picture;
        $this->shopGoods = $shopGoods;
        $this->waterBill = $waterBill;
        $this->memberWaterBill = $memberWaterBill;
        $this->order = $order;
        $this->wechatSet = $wechatSet;
        $this->member = $member;
        $this->notice = $notice;
        $this->waterBillOrder = $waterBillOrder;
        $this->shopAccount = $shopAccount;
        $this->smsLog = $smsLog;
        $this->silentAuth = $silentAuth;
        $this->privateCode = $privateCode;
        $this->referCode = $referCode;
        $this->saoPay = $saoPay;
    }

    // 获取微信用户信息
    public function getWxLogin()
    {
        $wechatSet = $this->wechatSet->_redisGetOneByAid(1);
        if (!$wechatSet) {
            return error('该商户配置信息未完善');
        }
        $code = request('code');
        $encryptedData = request('encryptedData');
        $iv = request('iv');
        $formId = request('formId');
        $appid = $wechatSet['xcx_app_id'];
        $secret = $wechatSet['xcx_app_secret'];
        $URL = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";
        $apiData = json_decode(file_get_contents($URL), true);
        if (isset($apiData['errcode'])) {
            return error('微信授权失败');
        }
        $errCode = $this->decryptData($appid, $apiData['session_key'], $encryptedData, $iv, $data);
        if ($errCode) {
            return error('获取用户微信数据失败');
        }
        $this->xcx_openid = $apiData['openid'];
        if ($this->xcx_openid) {
            $where['xcx_openid'] = $this->xcx_openid;
            $where['is_default'] = 1;
            $memberInfo = $this->member->_getOne($where);
            if ($memberInfo) {
                //存储用户formId
                $this->member->_redisSetFormId($memberInfo['id'], request('formId'));
                $shop = $this->shop->_getOne(['admin_id' => $this->admin_id, 'id' => $memberInfo['shop_id']], 'id,shop_name,status');
                if ($shop) {
                    $arr = [
                        'mid' => $memberInfo['id'],
                        'mobile' => $memberInfo['mobile'],
                        'xcx_openid' => $memberInfo['xcx_openid'],
                        'avatarurl' => $memberInfo['avatarurl'],
                        'nickname' => $memberInfo['nickname'],
                        'aid' => $this->admin_id,
                        'sid' => $shop['id'],//后期去掉
                        'shop_name' => $shop['shop_name'], //后期去掉;
//                        'formId' => $formId //后期去掉;
                    ];
                    return success($arr);
                }
            }
        }
        $token = md5($apiData['openid'] . '_' . $this->admin_id . '_' . date('Ymd'));
        $data = json_decode($data, true);
        $mdata['admin_id'] = $this->admin_id;
        $mdata['xcx_openid'] = $apiData['openid'];
        $mdata['nickname'] = $data['nickName'];
        $mdata['avatarurl'] = $data['avatarUrl'];
//        $mdata['unionId'] = $data['unionId'];
        $mdata['addtime'] = time();
        $shops = $this->shop->_getList(['admin_id' => $this->admin_id], 'id,shop_name')->toArray();
        if (count($shops) == 1) {
            //检查表单提交状态
            $key = 'regist_' . $apiData['openid'] . '_' . $this->admin_id . '_' . $shops[0]['id'];
            if ($this->redis->exists($key)) {
                return error('请勿重复操作');
            }
            $mdata['shop_id'] = $shops[0]['id'];
            $mdata['is_default'] = 1;
            $where = [
                'xcx_openid' => $apiData['openid'],
                'admin_id' => $this->admin_id,
                'shop_id' => $shops[0]['id'],
            ];
            $memberInfo = $this->member->_getOne($where, 'id');
            if (!$memberInfo) {
                $this->member->_validate($data);
                $res = $this->member->_save($mdata);
                if (!$res) {
                    return error('保存用户微信数据失败');
                }
                unset($mdata['addtime']);
                unset($mdata['is_default']);
                $mdata['mid'] = $res;
                $mdata['mobile'] = '';
                $mdata['aid'] = $this->admin_id;
                $mdata['sid'] = $shops[0]['id'];
                $mdata['shop_name'] = $shops[0]['shop_name']; //后期去掉;
                //储存表单提交状态
                $this->redis->setex($key, 120, 1);
                //存储用户formId
                $this->member->_redisSetFormId($res, request('formId'));
                return success($mdata, '操作成功');
            }
            return error('请勿重复操作');
        }
        $this->redis->setex($token, 3600, serialize($mdata));
        return success(['xcx_openid' => $apiData['openid'], 'token' => $token]);
    }

    public function postBindShop()
    {
        $xcx_openid = request('xcx_openid');
        $wx_openId = request('wx_openid');
        $token = request('token');
        if (!(($xcx_openid || $wx_openId) && $token && $this->shop_id)) {
            return error('非法操作');
        }
        $info = $this->redis->get($token);
        if (!$info) {
            return error('该操作已失效，请重新授权');
        }
        $info = unserialize($info);

        $shop = $this->shop->_getOne(['id' => $this->shop_id], 'id,admin_id,shop_name,status');
        if (!$shop) {
            return error('该店铺不存在');
        }
        $aid = $this->admin_id ? $this->admin_id : $shop['admin_id'];

        $memberInfo = $this->member->getMemberInfoByOpenId($xcx_openid, $wx_openId, $this->shop_id);
        if ($memberInfo) {
            $arr = [
                'mid' => $memberInfo['mid'],
                'mobile' => $memberInfo['mobile'],
                'xcx_openid' => isset($memberInfo['xcx_openid']) ? $memberInfo['xcx_openid'] : '',
                'wx_openid' => isset($memberInfo['wx_openid']) ? $memberInfo['wx_openid'] : '',
                'avatarurl' => $memberInfo['avatarurl'],
                'nickname' => $memberInfo['nickname'],
                'aid' => $aid,
                'sid' => $shop['id'],//后期去掉
                'shop_name' => $shop['shop_name'], //后期去掉;
            ];
            return success($arr, '操作成功');
        }
        // 判断是小程序员还是微信提交
        $mdata = $info;
        $mdata['shop_id'] = $this->shop_id;
        $mdata['is_default'] = 1;
        if ($xcx_openid) {
            $memberInfo = $this->member->_getOne(['xcx_openid' => $mdata['xcx_openid'], 'shop_id' => $this->shop_id]);
            $mid = $memberInfo ? $memberInfo['id'] : 0;
            if (!$memberInfo) {
                //检查表单提交状态
                $key = 'regist_' . $mdata['xcx_openid'] . '_' . $this->admin_id . '_' . $this->shop_id;
                if ($this->redis->exists($key)) {
                    return error('请勿重复操作');
                }
                $res = $this->member->_save($mdata);
                if (!$res) {
                    return error('保存用户微信数据失败');
                }
                //储存表单提交状态
                $this->redis->setex($key, 120, 1);
                $mid = $res;
                $where['id'] = ['<>', $res];
                $where['xcx_openid'] = $mdata['xcx_openid'];
                $this->member->_update($where, ['is_default' => 0]);
            }
        } else {
            $memberInfo = $this->member->_getOne(['wx_openid' => $mdata['wx_openid'], 'shop_id' => $this->shop_id]);
            if (!$memberInfo) {
                //检查表单提交状态
                $key = 'regist_' . $mdata['wx_openid'] . '_' . $this->admin_id . '_' . $this->shop_id;
                if ($this->redis->exists($key)) {
                    return error('请勿重复操作');
                }
                $mdata['admin_id'] = $aid;
                $res = $this->member->_save($mdata);
                if (!$res) {
                    return error('保存用户微信数据失败');
                }
                $this->redis->setex($key, 120, 1);
                $mid = $res;
                $where['id'] = ['<>', $mid];
                $where['wx_openid'] = $mdata['wx_openid'];
                $this->member->_update($where, ['is_default' => 0]);
            }
        }

        unset($mdata['addtime']);
        unset($mdata['is_default']);
        $mdata['mid'] = $mid;
        $mdata['mobile'] = '';
        $mdata['aid'] = $aid;
        $mdata['sid'] = $shop['id'];
        $mdata['shop_name'] = $shop['shop_name']; //后期去掉;

        return success($mdata, '操作成功');
    }

    public function getCheckShopStatus()
    {
        $shop = $this->shop->_redisGetOneBySid($this->shop_id);
        return success(['shop_status' => $shop['status']]);
    }

    public function getShopList()
    {
        $shop = $this->shop->_redisGetOneBySid($this->shop_id);
        if ($shop['status'] < 0) {
            $ajaxData['shop_list'] = [
                0 => [
                    'id' => 1,
                    'shop_name' => 1,
                    'slide_num' => 3,
                    'sliders' => [
                        0 => 'https://img.alicdn.com/imgextra/i2/22546475/TB2gSHhbFYM8KJjSZFuXXcf7FXa_!!22546475.jpg_970x970Q90s50.jpg_.webp',
                        1 => 'https://img.alicdn.com/tps/i4/TB126njgamgSKJjSsplSuuICpXa.jpg_970x970Q90s50.jpg_.webp',
                        2 => 'https://img.alicdn.com/tfs/TB11y9.q9tYBeNjSspaXXaOOFXa-1125-420.jpg_970x970Q90s50.jpg_.webp',
                    ],
                ],
            ];
            return success($ajaxData);
        }
        $ajaxData['shop_list'] = [];
        if ($this->admin_id) {
            $where['admin_id'] = $this->admin_id;
        } else {
            $where = [];
        }
        $shop_list = $this->shop->_getList($where, 'id,admin_id,shop_name,slide_num,area_info,address', ['id' => 'asc'])->toArray();
        if (!empty($shop_list)) {
            foreach ($shop_list as $k => $v) {
                $sliderpath = '/uploads/sliders/imgs/' . $v['admin_id'];
                $logopath = '/uploads/logos/imgs/' . $v['admin_id'];
                $ajaxData['shop_list'][$k] = [
                    'id' => $v['id'],
                    'shop_name' => $v['shop_name'],
                    'shop_logo' => url('/') . $logopath . '/' . $v['id'] . '_' . 1 . '.' . $this->picture->config['saveExt'] . '?time=' . time(),
                    'slide_num' => $v['slide_num'],
                    'area_info' => $v['area_info'],
                    'address' => $v['address']
                ];
               if ($v['slide_num']) {
                    for ($i = 1; $i <= $v['slide_num']; $i++) {
                        $path =  $sliderpath . '/' . $v['id'] . '_' . $i . '.' . $this->picture->config['saveExt'];
                        if (!file_exists(public_path($path))) {
                            $ajaxData['shop_list'][$k]['sliders'][] = url('/') .'/img/slider_img.jpg';
                        } else {
                            $ajaxData['shop_list'][$k]['sliders'][] = url('/') . $path . '?time=' . time();
                        }
                    }
                } else {
                    $ajaxData['shop_list'][$k]['sliders'][] = url('/') .'/img/slider_img.jpg';
                }
                if ($this->shop_id && $v['id'] == $this->shop_id) {
                    $arr['shop_list'][0] = $ajaxData['shop_list'][$k];
                    return success($arr);
                }
            }
        }
        return success($ajaxData);
    }

    public function getGoodsCategory()
    {
        $shop = $this->shop->_redisGetOneBySid($this->shop_id);
        if ($shop['status'] < 0) {
            $ajaxData['goods_category_list'] = config('goodsCategoryList');
            return success($ajaxData);
        }
        $ajaxData['goods_category_list'] = $this->goodsCategory->getParentCategory();
        return success($ajaxData);
    }

    public function getGoodsList()
    {
        $shop = $this->shop->_redisGetOneBySid($this->shop_id);
        if ($shop['status'] < 0) {
            $category = request('category_id');
            $category -= 1;
            $ajaxData['goods_list'] = [
                'next_page_url' => '',
                'data' => config('goodsList')[$category > 0 ? $category : 0]
            ];
            return success($ajaxData);
        }
        $ajaxData['goods_list'] = $this->shopGoods->_redisGetGoodsListByShopId($this->shop_id);
        if (isset($ajaxData['goods_list']['data']) && !empty($ajaxData['goods_list']['data'])) {
            if (request('category_id') && $ajaxData['goods_list']['next_page_url']) {
                $ajaxData['goods_list']['next_page_url'] = $ajaxData['goods_list']['next_page_url'] . '&category_id=' . request('category_id');
            }
            foreach ($ajaxData['goods_list']['data'] as $k => $v) {
                $ajaxData['goods_list']['data'][$k]['goods_img'] = url('/') . $this->picture->config['savePath'] . $this->admin_id . '/' . $v['goods_id'] . '_1.' . $this->picture->config['saveExt'] . '?time=' . time();
            }
        }
        return success($ajaxData);
    }

    public function getWaterBillList()
    {
        $shop = $this->shop->_redisGetOneBySid($this->shop_id);
        if ($shop['status'] < 0) {
            return error();
        }
        $where['shop_id'] = $this->shop_id;
        $ajaxData['goods_list'] = $this->waterBill->_redisGetBillListByShopId($this->shop_id);
        if (isset($ajaxData['goods_list']['data']) && !empty($ajaxData['goods_list']['data'])) {
            foreach ($ajaxData['goods_list']['data'] as $k => $v) {
                $ajaxData['goods_list']['data'][$k]['goods_img'] = url('/') . $this->picture->config['savePath'] . $this->admin_id . '/' . $v['goods_id'] . '_1.' . $this->picture->config['saveExt'] . '?time=' . time();
            }
        }
        return success($ajaxData);
    }

    public function getMemberWaterBillList()
    {
        $ajaxData['waterbill_list'] = $this->memberWaterBill->_redisGetBillListByMid($this->mid);
        if (isset($ajaxData['waterbill_list']) && !empty($ajaxData['waterbill_list'])) {
            foreach ($ajaxData['waterbill_list'] as $k => $v) {
                $ajaxData['waterbill_list'][$k]['goods_img'] = url('/') . $this->picture->config['savePath'] . $this->admin_id . '/' . $v['goods_id'] . '_1.' . $this->picture->config['saveExt'] . '?time=' . time();
            }
        }
        return success($ajaxData);
    }

    public function getOrderList()
    {
        $ajaxData['order_list'] = $this->order->getOrderListWithGoods();
        if (isset($ajaxData['order_list']) && !empty($ajaxData['order_list'])) {
            foreach ($ajaxData['order_list'] as $k => $v) {
                foreach ($v['orderGoods'] as $m => $n) {
                    $ajaxData['order_list'][$k]['orderGoods'][$m]['goods_img'] = url('/') . $this->picture->config['savePath'] . $this->admin_id . '/' . $n['goods_id'] . '_1.' . $this->picture->config['saveExt'] . '?time=' . time();
                }
            }
        }
        return success($ajaxData);
    }

    public function decryptData($appid, $sessionKey, $encryptedData, $iv, &$data)
    {
        $OK = 0;
        $IllegalAesKey = -41001;
        $IllegalIv = -41002;
        $IllegalBuffer = -41003;
        $DecodeBase64Error = -41004;

        if (strlen($sessionKey) != 24) {
            return $IllegalAesKey;
        }
        $aesKey = base64_decode($sessionKey);


        if (strlen($iv) != 24) {
            return $IllegalIv;
        }
        $aesIV = base64_decode($iv);

        $aesCipher = base64_decode($encryptedData);

        $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj = json_decode($result);
        if ($dataObj == NULL) {
            return $IllegalBuffer;
        }
        if ($dataObj->watermark->appid != $appid) {
            return $IllegalBuffer;
        }
        $data = $result;
        return $OK;
    }

    public function getShopInfo()
    {
        $shopInfo = $this->shop->_getOneById($this->shop_id, 'id,shop_name,area_info,address,contact,work_time,shop_position,send_area_radius,send_area,notice,bill_notice,pic_num');
        if ($shopInfo) {
            $shopInfo = $shopInfo->toArray();
            $this->picture->config['savePath'] = '/uploads/shops/imgs/';
            $path = $this->picture->config['savePath'] . $this->admin_id . '/' . $shopInfo['id'] . '_1.' . $this->picture->config['saveExt'];
            $shopInfo['shop_img'] = url('/') . $path . '?time=' . time();
            if (!file_exists(public_path($path))) {
                $shopInfo['shop_img'] = '';
            }
        }
        $ajaxData['info'] = $shopInfo;
        return success($ajaxData);
    }

    public function getNotice()
    {
        $res = $this->notice->_redisGetOneBySid($this->shop_id);
        return success($res);
    }

    public function getPayMethod()
    {
        $shopInfo = $this->shop->_redisGetOneBySid($this->shop_id);
        $ajaxData['pay_method'] = ['online_pay' => $shopInfo['online_pay'], 'offline_pay' => $shopInfo['offline_pay']];
        return success($ajaxData);
    }

    public function getTips()
    {
        abort(300, '该功能仅支持最新版手机端微信操作');
    }

    public function getWaterBillInfo()
    {
        $ajaxData['info'] = [];
//        $WaterBillData = $this->waterBill->_redisGetBillListByShopId($this->shop_id);
        $keys = $this->waterBill->_redisGetBillListKeysBySid($this->shop_id);
        $WaterBillData = $this->waterBill->_redisGetBillListByKeys($keys);
        if (!empty($WaterBillData)) {
            foreach ($WaterBillData as $v) {
                if (request('id') == $v['id']) {
                    $ajaxData['info'] = $v;
                    $ajaxData['info']['goods_img'] = url('/') . $this->picture->config['savePath'] . $this->admin_id . '/' . $v['goods_id'] . '_1.' . $this->picture->config['saveExt'] . '?time=' . time();
                }
            }
        }
        return success($ajaxData);
    }

    public function postCheckOrderStatus()
    {
        $type = request('type');
        if (!$type) {
            return error('非法操作');
        }
        $orderId = request('id');
        if (!$orderId) {
            return error('非法操作');
        }
        $res = false;
        if ($type == 1) {
            $orderInfo = $this->order->_getOneById($orderId, 'type,order_sn,status');
            if ($orderInfo['type'] == 0 && $orderInfo['status'] == 10) {
                $res = $this->order->dealOrder($orderInfo['order_sn']);
            }
        }
        if ($type == 2) {
            $orderInfo = $this->waterBillOrder->_getOneById($orderId, 'type,order_sn,pay_status');
            if ($orderInfo['type'] == 0 && $orderInfo['pay_status'] == 10) {
                $res = $this->waterBillOrder->dealOrder($orderInfo['order_sn']);
            }
        }
//        return success([$res]);
    }

    public function getEntrance()
    {
        $code = request('code');
        $private_code = request('private_code');
        $mid = request('mid');
        $settings = $this->wechatSet->_redisGetOneByAid(1);
        $weChat = new WechatLogin($settings['wx_app_id'], $settings['wx_app_secret']);
        $redirectUrl = request()->fullUrl();
        if (!$code) {
            $weChat->getCode($redirectUrl);
        } else {
            $userInfo = $weChat->get_user_info($code);
            if($private_code) {
                // 订水码功能
                $result = $this->privateCode->bindUserByCode($userInfo, $private_code);
                if($result['status']) {
                    Header("Location: {$result['msg']}");
                } else {
                    $msg = $result['msg'];
                    return view('errors.110',compact('msg'));
                }
                exit;
            } else if($mid ) {
                // 推广注册
                $this->referRegisterHandle($userInfo, $mid);
            }

            // 商店跳转
            $memberFields = 'id,shop_id,unionid';
            if (isset($userInfo['openid'])) {
                $member = $this->member->_getOne([
                    'wx_openid' => $userInfo['openid'],
                    'is_default' => 1,
                ],$memberFields);
                if (!$member) {
                    $msg = '扫描二维码，点击【关注公众号】进入！';
                    return view('errors.110',compact('msg'));
                    /*if (!$this->redis->get(md5($userInfo['openid']))) {
                        $data = [
                            'admin_id' => in_array($aid, [1, 2]) ? 2 : $aid, // 若无aid或aid = 1或2时,则admin_id 默认为2
                            'wx_openid' => $userInfo['openid'],
                            'unionid' => isset($userInfo['unionid']) ? $userInfo['unionid'] : '',
                            'nickname' => $userInfo['nickname'],
                            'avatarurl' => $userInfo['headimgurl'],
                            'addtime' => time(),
                            'created_at' => date('Y-m-d H:i:s')
                        ];
                        $key = md5($userInfo['openid']);
                        $this->redis->setex($key, 3600, serialize($data));
                    }
                    $url = url('/client/choose-shop.html?wx_openid=' . $userInfo['openid'] . "&token=" . md5($userInfo['openid']));*/
                } else {
                    if (isset($userInfo['unionid']) && $userInfo['unionid'] && !$member['unionid']) {
                        $res = $this->member->_update(['id' => $member['id']], ['unionid' => $userInfo['unionid']]);
                        if (!$res) {
                            return error('保存用户微信数据失败');
                        }
                    }
                    $member = json_decode($member, true);
                    $url = url('/client/take-water.html?_=' . time() . '&wx_openid=' . $userInfo['openid'] . '&sid=' . $member['shop_id']);
                }
                Header("Location: $url");
            }
        }
    }

    // 推广注册处理
    public function referRegisterHandle($userInfo, $mid = 0)
    {
        $referMember = $this->member->_getOneById($mid);
        $sid = $referMember['shop_id'];
        $memberInfo = $this->member->_getOne([
            'wx_openid' => $userInfo['openid'],
            'shop_id' => $sid
        ]);
        if($memberInfo && $memberInfo['is_default'] != 1) {
            $this->member->changeDefaultShopByMid($memberInfo['id']);
        }
        if(!$memberInfo) {
            $url = url('/client/refer.html?_='.time().'&mid='.$mid);
            header("Location: $url");
            exit;
        } else {
            $url = url('/client/take-water.html?_=' . time() . '&wx_openid=' . $userInfo['openid'] . '&sid=' . $sid);
            header("Location: $url");
            exit;
        }

    }

    public function postSimple()
    {
        $res = $this->shop->addOrUpdate();
        if (!$res) {
            return error($this->shop->getError() ? $this->shop->getError() : '新增失败');
        }
        return success();
    }

    public function getSmsCaptcha()
    {
        if (!check_verify(request('verify'))) {
            return error('验证码输入错误！');
        }
        $mobile = trim(request('mobile'));
        if (!$mobile) {
            return error('请填写手机号');
        }
        if (!is_mobile($mobile)) {
            return error('请填写正确手机号');
        }
        $type = request('type', 2);
        $res = $this->smsLog->getSmsCaptcha($mobile, $type, $this->mid);
        return $this->ajaxReturn($res);
    }

    public function getInviteMember()
    {
        $info = $this->wechatSet->_redisGetOneByAid(1);
        if ($info && $info['wx_app_id'] && $info['wx_app_secret']) {
            $data = json_encode([
                'shopId' => $this->shop_id,
                'action' => 'inviteMember' // 表示受邀注册
            ]);
            $key = 'member_share_shop_'.$this->mid;
            return $this->silentAuth->getTempQrCode($info['wx_app_id'], $info['wx_app_secret'], $key, $data);
        }
        return '';
    }

    public function getGoodsListWithBill()
    {
//        $this->shop_id = 1;
//        $this->admin_id = 1;
//        $this->mid = 100000;
        $where['shop_id'] = $this->shop_id;
        $where['status'] = 1;
        $order['sort'] = 'sort';
        $order['id'] = 'asc';
        $ajaxData['goods_list'] = $this->shopGoods->_getList($where, 'id,goods_id,goods_name,goods_num,goods_price', $order)->toArray();
        if (!$ajaxData['goods_list']) {
            return error('该商户没有商品');
        }
        foreach ($ajaxData['goods_list'] as $k => $v) {
            $ajaxData['goods_list'][$k]['bill_info'] = [];
            $ajaxData['goods_list'][$k]['goods_img'] = url('/') . $this->picture->config['savePath'] . $this->admin_id . '/' . $v['goods_id'] . '_1.' . $this->picture->config['saveExt'] . '?time=' . time();
        }
        $condition['mid'] = $this->mid;
        $fields = 'id,shop_goods_id,rest_num';
        $billList = $this->memberWaterBill->_getList($condition,$fields)->toArray();
        if ($billList) {
            foreach ($ajaxData['goods_list'] as $k=>$v) {
                foreach ($billList as $m) {
                    if ($m['shop_goods_id'] == $v['id'] && $m['rest_num'] > 1) {
                        $ajaxData['goods_list'][$k]['bill_info'] = $m;
                    }
                }
            }
            $arrTem1 = [];
            $arrTem2 = [];
            foreach ($ajaxData['goods_list'] as $v) {
                if ($v['bill_info']) {
                    $arrTem1[] = $v;
                } else {
                    $arrTem2[] = $v;
                }
            }
            $ajaxData['goods_list'] = array_merge($arrTem1,$arrTem2);
        }
        return success($ajaxData['goods_list']);
    }

    // 获取分销二维码图片
    public function getCommissionQr()
    {
        $memberInfo = $this->member->_getOneById(request('mid'));
        if(!$memberInfo) {
            return error('该用户不存在');
        }
        $shopInfo = $this->shop->_redisGetOneBySid($memberInfo['shop_id']);
        $settings = $this->wechatSet->_getOne(['admin_id' => 1]);

        $data = json_encode([
            'action' => 'refer',//用于标识推广码操作
            'shopId' => $memberInfo['shop_id'],
            'referMid' => $this->mid, //推广员ID
            'referId' => $memberInfo['refer_id'] // 推广码ID
        ]);

        $key = 'member_refer_shop_'.$this->mid;
        $tempQrUrl = (new WechatSilentAuth())->getTempQrCode($settings['wx_app_id'], $settings['wx_app_secret'], $key, $data);
        if($memberInfo['refer_type'] == 1) {
            $tempQrUrl = $this->referCode->personReferQr($tempQrUrl);
        }

        $ajaxData = [
            'qr' => $tempQrUrl,
            'shop_name' => $shopInfo ? $shopInfo['shop_name'] : ''
        ];
        return success($ajaxData);
    }

}
